package com.tt.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tt.entity.Question;
import com.tt.entity.Reply;
import com.tt.entity.User;
import com.tt.service.CommunityServiceImpl;

@Controller
public class CommunityController {
	@Resource
	private CommunityServiceImpl cImpl;
	@RequestMapping(value="addquestion", method=RequestMethod.POST)
	public Object addQuestion(Question question,Model model,HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		User user = (User) request.getSession().getAttribute("user");
		int uid=user.getId();
//		int uid=1;
		Date date = new Date();
		question.setDate(date);
		boolean addQuestion = cImpl.addQuestion(question, uid);
		if (addQuestion) {
			out.print("<script language='javascript'>alert('提交成功');window.location.href='lylist'</script>");
		}
		out.print("<script language='javascript'>alert('提交失败');window.location.href='lylist'</script>");
		return out;
	}
	@RequestMapping(value="addreply", method=RequestMethod.POST)
	public Object addQuestion(Model model,Reply reply,HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		Date date=new Date();
		reply.setDate(date);
		String parameter = request.getParameter("qid");
		int qid = Integer.parseInt(parameter);
		System.out.println(qid);
		User user = (User) request.getSession().getAttribute("user");
		int uid=user.getId();
//		int uid=2;
		boolean b = cImpl.addReply(qid, reply,uid);
		if (b) {
			List<Question> findAllQuestion = cImpl.findAllQuestion();
			model.addAttribute("findAllQuestion", findAllQuestion);
			out.print("<script language='javascript'>alert('回复成功');window.location.href='lylist'</script>");
		}
		out.print("<script language='javascript'>alert('回复失败');window.location.href='lylist'</script>");
		return out;
	}
	@RequestMapping(value="lylist")
	public String findAllQuestion(Model model){
		List<Question> findAllQuestion = cImpl.findAllQuestion();
		model.addAttribute("findAllQuestion", findAllQuestion);
		return "/lyb.jsp";
	}
}
